package com.tjec.project.system.service.impl;

import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.enums.CodeNum;
import com.tjec.common.enums.NumCode;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.SFtpUtil;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.file.FileNetUrl;
import com.tjec.common.utils.poi.ExcelUtil;
import com.tjec.common.utils.poi.ExcelVo;
import com.tjec.common.utils.poi.ImportExcelUtil;
import com.tjec.framework.security.service.TokenService;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.project.businessWorkbench.domain.BmsBusinessDocArchive;
import com.tjec.project.businessWorkbench.domain.ImportBmsBusinessTask;
import com.tjec.project.system.domain.BmsAttachment;
import com.tjec.project.system.domain.BmsCategoryAssociated;
import com.tjec.project.system.domain.BmsMdBusinessCategory;
import com.tjec.project.system.domain.BmsMdTaskTemplate;
import com.tjec.project.system.domain.BmsTaskTemplateList;
import com.tjec.project.system.domain.vo.BmsAttachmentVo;
import com.tjec.project.system.mapper.BmsAttachmentMapper;
import com.tjec.project.system.mapper.BmsCategoryAssociatedMapper;
import com.tjec.project.system.mapper.BmsMdBusinessCategoryMapper;
import com.tjec.project.system.mapper.BmsMdTaskTemplateMapper;
import com.tjec.project.system.mapper.BmsTaskTemplateListMapper;
import com.tjec.project.system.service.IBmsAttachmentService;
import com.tjec.project.system.service.IBmsMdTaskTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 任务模板Service业务层处理
 *
 * @author tjec
 * @date 2020-04-09
 */
@Service
public class BmsMdTaskTemplateServiceImpl implements IBmsMdTaskTemplateService {
    @Autowired
    private BmsMdTaskTemplateMapper bmsMdTaskTemplateMapper;
    @Autowired
    private IBmsAttachmentService iBmsAttachmentService;
    @Autowired
    private BmsAttachmentMapper bmsAttachmentMapper;
    @Autowired
    private BmsCategoryAssociatedMapper bmsCategoryAssociatedMapper;
    @Autowired
    private BmsMdBusinessCategoryMapper bmsMdBusinessCategoryMapper;
    @Autowired
    private SFtpUtil sftp;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private BmsTaskTemplateListMapper bmsTaskTemplateListMapper;

    /**
     * 查询任务模板
     *
     * @param guid 任务模板ID
     * @return 任务模板
     */
    @Override
    public BmsMdTaskTemplate selectBmsMdTaskTemplateById(String guid) {
        BmsMdTaskTemplate entity = bmsMdTaskTemplateMapper.selectBmsMdTaskTemplateById(guid);
        if (StringUtils.isNotBlank(entity.getAttachmentId())) {
            //附件
            entity.setAttachmentList(iBmsAttachmentService.selectBmsAttachmentDownload(entity.getAttachmentId()));
        }
        //业务类型
        List<BmsMdBusinessCategory> bmsMdBusinessCategoryList = bmsMdBusinessCategoryMapper.selectBusinessCategoryByCategoryAssociated(guid, null);
        entity.setBusinessCategoryList(bmsMdBusinessCategoryList);
        //转化guid成List<String>
        List<String> lists = new ArrayList<String>();
        for (BmsMdBusinessCategory bmsMdBusinessCategory : bmsMdBusinessCategoryList) {
            lists.add(bmsMdBusinessCategory.getGuid());
        }
        entity.setBusinessCategoryIds(lists);
        return entity;
    }

    /**
     * 查询任务模板列表
     *
     * @param bmsMdTaskTemplate 任务模板
     * @return 任务模板
     */
    @Override
    public List<BmsMdTaskTemplate> selectBmsMdTaskTemplateList(BmsMdTaskTemplate bmsMdTaskTemplate) {
        List<BmsMdTaskTemplate> list = bmsMdTaskTemplateMapper.selectBmsMdTaskTemplateList(bmsMdTaskTemplate);
        list.forEach(item -> {
            if (StringUtils.isNotBlank(item.getAttachmentId())) {
                item.setAttachmentList(iBmsAttachmentService.selectBmsAttachmentDownload(item.getAttachmentId()));
            }
            item.setBusinessCategoryList(bmsMdBusinessCategoryMapper.selectBusinessCategoryByCategoryAssociated(item.getGuid(), bmsMdTaskTemplate.getBusinessCategoryId()));
        });
        return list;
    }

    /**
     * 新增任务模板
     *
     * @param bmsMdTaskTemplate 任务模板
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int insertBmsMdTaskTemplate(BmsMdTaskTemplate bmsMdTaskTemplate) {
        bmsMdTaskTemplate.setCreateTime(DateUtils.getNowDate());
        int ret = bmsMdTaskTemplateMapper.insertBmsMdTaskTemplate(bmsMdTaskTemplate);
        if (ret > -1) {
            updateAttachment(bmsMdTaskTemplate);
            updateBusinessCategory(bmsMdTaskTemplate);
            
            //插入任务管理清单模板内容
            bmsMdTaskTemplate.setBusinessCategoryId(StringUtils.join(bmsMdTaskTemplate.getBusinessCategoryIds(),","));
            insertBatchTaskList(bmsMdTaskTemplate,"1");
        }


        return ret;
    }
    
    public void insertBatchTaskList(BmsMdTaskTemplate bmsMdTaskTemplate,String flag) {//1:新增，2:修改
    	if(com.tjec.common.utils.StringUtils.isNotBlank(bmsMdTaskTemplate.getAttachmentId())) {
    		//如果是修改，需要判断附件是否变化
    		if("2".equals(flag)) {
    			//获取原来的数据
    			bmsTaskTemplateListMapper.deleteBmsTaskTemplateListByTemplateId(bmsMdTaskTemplate.getGuid());
    		}
    		
    		List<BmsAttachmentVo> attachments = iBmsAttachmentService.selectBmsAttachmentDownload(bmsMdTaskTemplate.getAttachmentId());
    		if (CollectionUtils.isEmpty(attachments)) {
				return;
			}

			StringBuffer sb = new StringBuffer(attachments.get(0).getStoragePath());
			
			File file = null;
			if (attachments.get(0).getStoragePath().startsWith("https://")) {
				file = FileNetUrl.getNetUrlHttps(sb.toString());
			} else {
				file = FileNetUrl.getNetUrlHttp(sb.toString());
			}
			FileInputStream inputStream;
			try {
				inputStream = new FileInputStream(file);
				List<List<Object>> list = ImportExcelUtil.getBankListByExcel(inputStream, "前期咨询-任务管理清单模板文件.xlsx");

				List<BmsTaskTemplateList> bmsTaskTemplateLists = new ArrayList<BmsTaskTemplateList>();
				
				String[] businessTypeIds = StringUtils.split(bmsMdTaskTemplate.getBusinessCategoryId(),",");
				for (String string : businessTypeIds) {
					for (int i = 0; i < list.size(); i++) {
						BmsTaskTemplateList bmsTaskTemplateList = new BmsTaskTemplateList();
						bmsTaskTemplateList.setCreateBy(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
						bmsTaskTemplateList.setBusinessTypeId(string);
						bmsTaskTemplateList.setTemplateId(bmsMdTaskTemplate.getGuid());
						
						for (int j = 0; j < list.get(i).size(); j++) {
							if (j == 0) {
								bmsTaskTemplateList.setFirstTaskName(list.get(i).get(j).toString());
							} else if (j == 1) {
								bmsTaskTemplateList.setSecondTaskName(list.get(i).get(j).toString());
							} else if (j == 2) {
								bmsTaskTemplateList.setThirdTaskName(list.get(i).get(j).toString());
							} else if (j == 3) {
								bmsTaskTemplateList.setMilestone(list.get(i).get(j).toString());
							}

						}
						bmsTaskTemplateLists.add(bmsTaskTemplateList);
					}
				}
				
				bmsTaskTemplateListMapper.insertBmsTaskTemplateLists(bmsTaskTemplateLists);
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	
    }

    /**
     * 更新业务类别表
     *
     * @param entity
     */
    private void updateBusinessCategory(BmsMdTaskTemplate entity) {
        if (!CollectionUtils.isEmpty(entity.getBusinessCategoryIds())) {
            List<String> categoryList = entity.getBusinessCategoryIds();
            //添加关联库的数据  业务类别的关联
            for (String bms : categoryList) {
                BmsCategoryAssociated associated = new BmsCategoryAssociated();
                associated.setCategoryGuid(bms);
                associated.setParentGuid(entity.getGuid());
                associated.setGuid(UUID.randomUUID().toString());
                associated.setFlag(CodeNum.THREE.getCode());
                bmsCategoryAssociatedMapper.insertBmsCategoryAssociated(associated);
            }
        }
    }

    /**
     * 新增、修改时更新文件表
     *
     * @param entity
     */
    private void updateAttachment(BmsMdTaskTemplate entity) {
        if (StringUtils.isNotBlank(entity.getAttachmentId())) {
            BmsAttachment bmsAttachment = new BmsAttachment();
            bmsAttachment.setGuid(entity.getAttachmentId());
            bmsAttachment.setBizId(entity.getGuid());
            bmsAttachment.setDelFlag(NumCode.ZERO.getCode());
            bmsAttachment.setCategory(AttachmentConstants.TASK_TEMPLATE);
            iBmsAttachmentService.updateBmsAttachment(bmsAttachment);
        }
    }

    /**
     * 修改任务模板
     *
     * @param bmsMdTaskTemplate 任务模板
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateBmsMdTaskTemplate(BmsMdTaskTemplate bmsMdTaskTemplate) {
        bmsMdTaskTemplate.setUpdateTime(DateUtils.getNowDate());
        int ret = bmsMdTaskTemplateMapper.updateBmsMdTaskTemplate(bmsMdTaskTemplate);
        if (ret > -1) {
            bmsAttachmentMapper.updateBmsAttachmentByBizId(new String[]{bmsMdTaskTemplate.getGuid()}, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
            updateAttachment(bmsMdTaskTemplate);

            //对业务类别进行修改先删除在重现添加
            bmsCategoryAssociatedMapper.deleteBmsCategoryAssociatedByParentId(bmsMdTaskTemplate.getGuid());
            updateBusinessCategory(bmsMdTaskTemplate);
            bmsMdTaskTemplate.setBusinessCategoryId(StringUtils.join(bmsMdTaskTemplate.getBusinessCategoryIds(),","));
            insertBatchTaskList(bmsMdTaskTemplate,"2");
        }
        return ret;
    }

    /**
     * 批量删除任务模板
     *
     * @param guids 需要删除的任务模板ID
     * @return 结果
     */
    @Override
    public int deleteBmsMdTaskTemplateByIds(String[] guids) {
    	bmsTaskTemplateListMapper.deleteBmsTaskTemplateListByTemplateIds(guids);
        return bmsMdTaskTemplateMapper.deleteBmsMdTaskTemplateByIds(guids);
    }

    /**
     * 删除任务模板信息
     *
     * @param guid 任务模板ID
     * @return 结果
     */
    @Override
    public int deleteBmsMdTaskTemplateById(String guid) {
        return bmsMdTaskTemplateMapper.deleteBmsMdTaskTemplateById(guid);
    }

    @Override
    public AjaxResult validation(String fileUrl) throws Exception {
        Boolean ret = false;
        String path = fileUrl.substring(0, fileUrl.lastIndexOf("/") + 1);
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        sftp.connectServer();
        InputStream in = sftp.download(path, fileName);
        //InputStream in = new FileInputStream(fileUrl);
        ExcelUtil<ExcelVo> util = new ExcelUtil<ExcelVo>(ExcelVo.class);
        List<ExcelVo> list = util.toList(in, fileName, 0, 4);
        //数据校验
        if (!CollectionUtils.isEmpty(list)) {

            //四级任务列表
            List<ExcelVo> fourthTaskList = list.stream().filter(a -> StringUtils.isBlank(a.getString4())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(fourthTaskList)) {
                return AjaxResult.error("里程碑为必填项，不能为空");
            }
            //一级列表
            if (list.stream().anyMatch(a -> StringUtils.isBlank(a.getString1()))) {
                return AjaxResult.error("一级任务为必填项，不能为空");
            }
            //一级列表
            List<String> firstList = list.stream().filter(a -> StringUtils.isBlank(a.getString2()) && StringUtils.isNotBlank(a.getString1())).map(ExcelVo::getString1).collect(Collectors.toList());
            //二级任务列表
            List<ExcelVo> secondTaskList = list.stream().filter(a -> StringUtils.isNotBlank(a.getString2())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(secondTaskList)) {
                for (ExcelVo vo : secondTaskList) {
                    if (!firstList.contains(vo.getString1())) {
                        return AjaxResult.error("登记二级任务时，必须填写此项任务所属的一级任务");
                    }
                }
            }
            //二级列表
            List<String> secondList = list.stream().filter(a -> StringUtils.isBlank(a.getString3()) && StringUtils.isNotBlank(a.getString2())).map(ExcelVo::getString2).collect(Collectors.toList());
            //三级任务列表
            List<ExcelVo> thirdTaskList = list.stream().filter(a -> StringUtils.isNotBlank(a.getString3())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(thirdTaskList)) {
                for (ExcelVo vo : thirdTaskList) {
                    if (!secondList.contains(vo.getString2())) {
                        return AjaxResult.error("登记三级任务时，必须填写此项任务所属的二级任务");
                    }
                }
            }
            return AjaxResult.success();
        }
        return AjaxResult.error("模板数据格式不正确，请按要求填写");
    }
}
